var mongoose = require('./db.js');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
  username: { type: String }, //用户账号
  userpwd: { type: String }, //密码
  userage: { type: Number }, //年龄
  logindate: { type: Date } //最近登录时间
});
var User = mongoose.model('User', UserSchema);

function saveUser(data) {
  var user = new User({
    username: data.account, //用户账号
    userpwd: data.password, //密码
    userage: data.age, //年龄
    logindate: new Date() //最近登录时间
  });

  user.save(function(err, res) {
    if (err) {
      console.log("Error:" + err);
    } else {
      console.log("Res:" + res);
    }
  });
};

function getUserByName(name){
  var callbackObj = new Promise(function(resolve,reject){

    var findObject = {username:name};
    User.findOne(findObject,function(err,res){
      if (err) {
        reject({status:1,msg:'数据库错误',result:err});
      }
      else {
        resolve({status:0,msg:'操作成功',result:res});
      };
    });

  });
  return callbackObj;
};
//status 0 成功 status 1 错误
module.exports = {
  saveUser: saveUser,
  getUserByName: getUserByName,
};
